import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import payBehavior from "./payBehavior";

import dayjs from "dayjs";
import { bookingPreOrder, createOrder } from "@src/api/booking";
import color from "@src/common/color";
import router from "@src/router";
import { getWxaMsgTpl } from "@src/api/base";
import wxUtils from "@src/common/wxUtils";
import member from "@src/store/member";
import base from "@src/store/base";

Component({
  behaviors: [storeBindingsBehavior, payBehavior],
  storeBindings: [{
    store: member,
    fields: ['isMember', 'phone'],
  }, {
    store: base,
    fields: ['themeColor', 'themeTitleColor'],
  }],
  data: {
    productNo: null,
    beginDay: null,
    endDay: null,
    dateInfo: null,
    num: 1,
    tips: null,
    payChannels: null,
    product: null,
    shopInfo: null,
    refundRule: null,
    discountInfo: null,
    payRule: null,
    arrivalTime: null,
    accountInfo: null,
    price: [],
    storeNo: null,
    inpDisabled:'',
  },
  observers: {
    'themeColor': function (themeColor) {
      if (!themeColor) {
        return;
      }
      this.setData({ 'themeColorRgba': color.HexToRGB(themeColor, 5) })
    }
  },
  methods: {
    onLoad(options) {
      let { productNo, beginDay, endDay } = options;
      if (!beginDay || !endDay) {
        beginDay = null;
        endDay = null;
      }
      this.setData({ productNo, beginDay, endDay });
      this.parseDateInfo(beginDay, endDay)
      this.fetchData();
      this.$pay = this.selectComponent("#pay");
      this.$form = this.selectComponent("#user-form")
    },
    parseDateInfo(beginDay, endDay) {
      if (beginDay && endDay) {
        // 解析到店日期，用于全日房页面显示
        let weeks = ['日', '一', '二', '三', '四', '五', '六']
        beginDay = dayjs(beginDay, 'YYYY-MM-DD')
        endDay = dayjs(endDay, 'YYYY-MM-DD')
        let days = endDay.diff(beginDay, 'day')
        let dateInfo = {
          days: days,
          beginDay: [beginDay.format("MM"), beginDay.format("DD"), weeks[beginDay.day()]],
          endDay: [endDay.format("MM"), endDay.format("DD"), weeks[endDay.day()]]
        }
        this.setData({ dateInfo: dateInfo })
      }
    },
    fetchData: function () {
      let data = {
        productNo: this.data.productNo,
        beginDay: this.data.beginDay,
        endDay: this.data.endDay,
      }
      getWxaMsgTpl({ bizCode: "BOOKING_PLACE_ORDER" }).then(res => {
        this.setData({ tmplIds: res.data })
      })
      return bookingPreOrder(data).then(res => {
        if (res.code === 0) {
          let preOrder = res.data;
          let payChannels = []
          let tempList = preOrder.payRule.payChannels.split(",")
          for (let i = 0; i < tempList.length; i++) {
            if (tempList[i] === '0') {
              payChannels.push("wx")
            } else if (tempList[i] === '1') {
              payChannels.push("balance")
            }
          }
          this.setData({
            tips: preOrder.tips,
            product: preOrder.product,
            shopInfo: preOrder.shopInfo,
            refundRule: preOrder.refundRule,
            payRule: preOrder.payRule,
            payChannels: payChannels,
            price: preOrder.price,
            storeNo:preOrder.shopInfo.storeNo
          })
        }
      })
    },
    handleBeginDayChange(e) {
      this.setData({ beginDay: e.detail })
    },
    handleReduce() {
      if (this.data.num === 1) {
        return;
      }
      this.setData({ num: this.data.num - 1 > 0 ? this.data.num - 1 : 1 })
    },
    // handleAdd() {
    //   if (this.data.num >= 30) {
    //     return;
    //   }
    //   this.setData({ num: this.data.num + 1 < 30 ? this.data.num + 1 : 30 })
    // },
    handleAdd() {
      const accountInfo = wx.getAccountInfoSync();
      let appid = accountInfo.miniProgram.appId;
      let maxNum;
      if(appid==='wx10b139e105bed92e'){
        maxNum = 1
      }else {
        maxNum = 10
      }
      if (this.data.num >= maxNum) {
        wx.showToast({
          title:"已达到最大数量",
          icon:"none"
        })
        return;
      }
      this.setData({ num: this.data.num + 1 < maxNum ? this.data.num + 1 : maxNum })
    },
    handleToTips() {
      wx.createSelectorQuery().select(".policeAndNotice").boundingClientRect(res => {
        wx.pageScrollTo({
          scrollTop: res.top - 50,
          duration: 300
        })
      }).exec();
    },
    createOrder(orderForm) {
      if (this.data.order) {
        return;
      }
      createOrder(orderForm).then(res => {
        console.log('预订orderForm--',res)
        // wx.hideLoading();
        if (res.code === 0) {
          let { orderNo, payFee } = res.data
          let data = { orderNo: orderNo, payFee: payFee, hasDiscount: !!orderForm.discountInfo }
          // 调用payBehavior.toPay
          this.toBookingPay(data).then(res => {
            console.info("成功", res)
            wx.showLoading({ title: "支付成功, 跳转中...", mask: true });
            setTimeout(res => {
              wx.hideLoading();
              router.redirectTo({ name: 'booking/orderDetail', params: { orderNo: orderNo } });
            }, 300)
          }).catch(res => {
            console.error("支付失败", res)
            router.redirectTo({ name: 'booking/orderDetail', params: { orderNo: orderNo } });
          })
        }
      }).finally(()=>{
        wx.hideLoading()
      })
    },
    handlePay(e) {
      if (!this.$form.check()) {
        return;
      }
      let form = this.$form.getForm();
      let payInfo = e.detail;
      let orderForm = {
        ...form,
        ...payInfo,
        productNo: this.data.product.productNo,
        num: this.data.num,
        beginDay: this.data.beginDay,
        endDay: this.data.endDay,
        storeNo:this.data.storeNo
      };
      console.log('orderForm', orderForm);
      if (!orderForm.arrivalTimeMinute) {
        wx.showToast({
          title: '请填写到店时间',
          icon: 'none',
          duration: 2000
        }); return;
      }
      wx.showLoading({ title: "加载中...", mask: true });
      if (this.data.tmplIds) {
        wxUtils.requestSubscribeMessage(this.data.tmplIds).then(() => {
          this.createOrder(orderForm);
        }).catch(() => {
          this.createOrder(orderForm);
        })
      } else {
        this.createOrder(orderForm);
      }
      this.setData({
        inpDisabled:true
      })
    }
  }
})
